package com.lucaswangdev.myswitch.server;

import com.google.gson.Gson;
import spark.Request;
import spark.Response;
import spark.Spark;

import java.util.HashMap;
import java.util.Map;

/**
 * 简单的配置中心服务器，用于测试MySwitch SDK
 */
public class ConfigServer {
    private static final Map<String, Map<String, String>> configStore = new HashMap<>();
    private static final Gson gson = new Gson();
    
    public static void main(String[] args) {
        // 初始化一些测试配置
        Map<String, String> appConfig = new HashMap<>();
        appConfig.put("feature.enabled", "true");
        appConfig.put("timeout", "5000");
        appConfig.put("max.connections", "100");
        configStore.put("test-app:default", appConfig);
        
        // 启动HTTP服务器
        Spark.port(8080);
        
        // 获取配置的接口
        Spark.get("/config/:appId/:namespace", (request, response) -> {
            String appId = request.params(":appId");
            String namespace = request.params(":namespace");
            String key = appId + ":" + namespace;
            
            Map<String, String> config = configStore.getOrDefault(key, new HashMap<>());
            return gson.toJson(config);
        });
        
        // 更新配置的接口
        Spark.post("/config/:appId/:namespace", (request, response) -> {
            String appId = request.params(":appId");
            String namespace = request.params(":namespace");
            String key = appId + ":" + namespace;
            
            // 获取现有的配置
            Map<String, String> existingConfig = configStore.getOrDefault(key, new HashMap<>());
            
            // 解析请求体中的配置更新
            Map<String, String> updates = gson.fromJson(request.body(), Map.class);
            
            // 合并更新到现有配置
            existingConfig.putAll(updates);
            
            // 保存更新后的配置
            configStore.put(key, existingConfig);
            
            response.status(200);
            return "OK";
        });
        
        System.out.println("Config server started on port 8080");
    }
}